import * as mobx from 'mobx';
import { observable, action, useStrict, computed, asMap } from 'mobx';
import BaseStore from './base';
import * as API_REQ from '../apis/req';
import base from '../util/base';
import * as Util from '../util/formUtil';
import * as continuationProcessUtil from '../util/continuationProcessUtil';
import * as _ from '../util/public/common';
import * as GlobalUtil from '../util/public/globalUtil';
import { getInvoiceCloudToken } from './../util/public/invoiceUtil'
import loadjs from 'loadjs';
import objectAssign from 'object-assign';
import { getAntd, getEcCom } from '../util/convert';
import * as authTypes from "../constants/secondAuthType";
import { doFileUpload } from "../util/submit";
import { doFreeWorkflow } from "../util/rightBtn";
import { cloneDeep } from 'lodash';
import * as type  from '../constants/type';
const { WeaTools, WeaLocaleProvider } = getEcCom();
const { ls } = WeaTools;

//useStrict(true);
export class GlobalStore extends BaseStore {
    @observable JSComplete = false;     //标识完整组件库资源是否加载完成
    JSCompleteEvent = [];
    browserVersion = "";
    urlParams = {};

    @observable loading = false;
    @observable tabKey = "form";
    @observable btnDisabled = true;
    @observable apiBtnDisabled = false;
    @computed get baseParam() {  //基础参数
        let baseParam = {}
        GlobalUtil.baseParamRange.map(k => {
            baseParam[k] = this.commonParam[k];
        });
        return baseParam;
    }
    @computed get commonApiParam() {     //常用参数，供后端API接口调用
        let apiParam = {}
        GlobalUtil.commonApiParamRange.map(k => {
            apiParam[k] = this.commonParam[k];
        });
        return apiParam;
    }
    @computed get belongUserStr() {
        const { f_weaver_belongto_userid, f_weaver_belongto_usertype } = this.commonParam;
        return `&f_weaver_belongto_userid=${f_weaver_belongto_userid}&f_weaver_belongto_usertype=${f_weaver_belongto_usertype}`;
    }
    @computed get isSourceLayout() {
        const { layoutversion } = this.commonParam;
        return layoutversion === 0 || layoutversion === 1;
    }
    commonParam = {};       //常用有效参数
    invalidParam = {};      //剩余无效参数,后期去掉
    @observable submitParam = {};

    @observable markInfo = {};  //签字意见输入框相关信息
    closeNeedPrompt = true;     //离开表单是否提示
    @observable rightMenu = {};     //右键菜单
    @observable dialogVisible = observable.map ? observable.map({}) : asMap({});    //弹窗显示属性
    @observable invertionInfo = {}; //流程干预
    @observable promptInfo = {};    //顶部提示信息
    @observable remindInfo = {};    //提醒信息
    @observable secondAuthInfo = {};    //数据保护验证的信息
    @observable secLevelInfo = {};//密级信息
    @observable submitSelected = 0;
    @observable freeNodeDatas=[];
    @observable relatedProcess
    @action
    setProperty=(map)=>{
      Object.assign(this,map);
    }
    
    @observable continuationProcessInfo = {};//流程连续处理信息
    @observable conflictFieldMap =  observable.map ? observable.map({}): asMap({}); //表单冲突字段
	@observable btnLabelName = {}; //签字意见框按钮显示名称
    
    constructor() {
        super();
        this.browserVersion = Util.getBrowserVersion();
    }


    @action('控制JS是否异步加载完成')
    markJSComplete = () => {
        this.JSComplete = true;
    }

    @action('添加全量组件库加载完后才能执行的事件')
    pushJSCompleteEvent = (fn) => {
        if (typeof fn === "function") {
            if (this.JSCompleteEvent instanceof Array)
                this.JSCompleteEvent.push(fn);
            else    //已经执行过一次的情况，直接触发
                fn();
        }
    }

    @action('执行加载完事件，仅触发一次，触发完立即清除')
    triggerJSCompleteEvent = () => {
        if (this.JSComplete === true && this.JSCompleteEvent instanceof Array) {
            this.JSCompleteEvent.map(fn => {
                fn();
            });
            this.JSCompleteEvent = null;    //赋值非数组，标识已执行过
        }
    }

    @action('控制加载条')
    setLoading = (bool = false) => {
        this.loading = bool;
    }

    @action('控制按钮置灰')
    setBtnDisabled = (bool = true) => {
        this.btnDisabled = bool;
    }

    @action('API控制按钮置灰')
    setApiBtnDisabled = (bool = true) => {
        this.apiBtnDisabled = bool;
    }

    @action("控制发票云参数")
    setInvoiceCloudInfo = (invoiceCloudInfo) => {
        this.invoiceCloudInfo = invoiceCloudInfo;
    }

    @action('控制当前显示tab')
    setTabKey = (key) => {
        if (_.isEmpty(this.commonParam)) return;
        this.signReplyFlag = false; //清空回复的状态
        this.signReplyInfo = {}; //清空被回复人的信息
        this.tabKey = key;
        //记录tab项是否已点击过
        const variableKey = `haveClick_${key}`;
        !this.variableMap.has(variableKey) && this.controlVariableMap(variableKey, true);
    }

    @action('发送接口加载数据')
    loadBaseInfo = (queryParams) => {
        this.setLoading(true);
        window.API_LOAD_BEGIN = new Date().getTime();
        this.urlParams = queryParams;
		
		//弹出连续处理切换提示
        this.pushJSCompleteEvent(() => {
            continuationProcessUtil.showConProcessSwitchTip(queryParams);
        });
		
        if(this.urlParams.isPreView === "1")
            return this.loadPreViewInfo();
        API_REQ.loadBaseInfo(queryParams).then(data => {
            window.API_LOAD_END = new Date().getTime();
            window.API_DURATION = window.API_LOAD_END - window.API_LOAD_BEGIN;
            window.SERVER_DURATION = data.durationTime;
            delete queryParams["preloadkey"];
            delete queryParams["_key"];
            this.urlParams = queryParams;
            this.doInit(queryParams, data);
            if(data.conflictFieldInfo && typeof data.conflictFieldInfo == 'object')  {
              this.changeConflictFieldMap(data.conflictFieldInfo);
            }
            this.relatedProcess = data.relatedProcess
            // if (data.odocInfo.docFlag && data.odocInfo.isInnerChange == '1') {
            //     this.addInnerChangeBtn = true;
            // }
        });
    }

    @action('加载表单信息')
    doInit = (queryParams, data) => {
        this.setLoading(false);
        const params = data.params;
        //无权限跳转
        if (params.verifyRight === false) {
            weaWfFormHistory && weaWfFormHistory.push("/main/workflow/ReqNoRight?isSecNoRight=" + params.isSecNoRight + "&isDelete=" + params.requestIsDelete+"&isTest="+params.isTest);
            return;
        }
        //设置有效常用参数
        GlobalUtil.commonParamRange.map(v => {
            if (v in params) {
                this.commonParam[v] = params[v];
                delete params[v];
            }
        });

        //剩余无效参数(后期逐步去掉)
        this.invalidParam = params;
        //加载自定义样式文件
        GlobalUtil.loadCustomFiles("css");
        this.submitParam = data.submitParams;
        //初始化模板及表单内容
        base.layoutStore.doInitLayout(data);
		
        Util.printDuration(this.commonParam, true);
        //更新请求信息及刷新待办，快速处理信息加载完毕后，再执行
        let updateReqInfoFunc = () => {
            const { requestid, iscreate, nodetype, wfmonitor, isurger, isprint } = this.commonParam;
            if (iscreate != "1" && isprint != '1') {
                const { submitParams = {} } = data;
                let updateReqInfoParams = { ...submitParams, requestid: requestid, currentnodetype: nodetype, wfmonitor: wfmonitor, isurger: isurger,...GlobalUtil.getUpdateReqInfoFieldValue()};
                API_REQ.updateReqInfo(updateReqInfoParams).then(data => {
                    //传参刷新列表，列表再依赖参数判断是否刷新
                    this.pushJSCompleteEvent(() =>{
                        Util.reloadListPage({ from: "openReq", needReloadList: this.commonParam.needReloadList });
                    });
                });
            }
        }
        //加载顶部快速处理信息
        this.loadContinuationProcessInfo(queryParams, updateReqInfoFunc);
        //设置顶部提示信息
        this.promptInfos = data.promptInfos;
        //设置提醒类型信息
        this.remindInfo = data.remindInfo;
        //数据保护的验证信息
        this.secondAuthInfo = data.secondAuthInfo;
        //加载右键菜单
        this.loadRightMenu(queryParams);
        //加载签字意见输入框信息
        this.loadMarkInfo();
        //加载流程干预
        this.loadInterventionInfo();
        //tab扩展
        this.loadCustomTab();
        //显示CA认证的窗口
        this.showCAAuthDialog(data);
        //密级信息
        this.secLevelInfo = data.secLevelInfo;
        //请求当前流程拥有的关注标签
        this.getFormAttentionTag();
        //加载水印
        this.pushJSCompleteEvent(Util.loadWaterMark);
        //加载发票云token
        if(this.commonParam.useInvoiceCloud == true){
            getInvoiceCloudToken();
        }
    }

    @action('模板预览加载数据')
    loadPreViewInfo = () =>{
        const preViewKey = this.urlParams.preViewKey;
        if(window.sessionStorage.getItem(preViewKey)){
            const preViewData = JSON.parse(window.sessionStorage.getItem(preViewKey));
            API_REQ.loadPreViewInfo(preViewData).then(data =>{
                console.log("preViewData", preViewData, "data", data);
                this.commonParam = data.params;
                base.layoutStore.doInitLayout(data);
            });
        }else{
            alert(`loadPreViewInfo Catch Exception: ${preViewKey}`);
        }
    }

    //打开CA认证的窗口
    showCAAuthDialog = (data) => {
        const isCAAuth = this.urlParams.isCAAuth;
        const CAKey = this.urlParams.CAKey;
        if (isCAAuth == "1") {
            const { secondAuthStore } = base;
            const { secondAuthConfig } = data;
            const { qysSignWay = 2, protectType } = secondAuthConfig;
            secondAuthStore.setCallbackFunc(doFileUpload);

            if (!!CAKey) {      //从缓存中先读取之前的数据
                secondAuthStore.readDataFromStorage(CAKey);
            }
            secondAuthStore.setParams(secondAuthConfig);

            if (protectType == authTypes.QYS && qysSignWay == 1) {
                window.QYSUKeyUtil.showSignWin(secondAuthStore);
            } else if (protectType == authTypes.CA_AUTH) {
                this.controlDialogVisible(authTypes.SECOND_AUTH_DIALOG, true);
            }
        }
    }

    @action('加载右键菜单')
    loadRightMenu = (queryParams) => {
        const params = { ...this.commonApiParam };
        //提交确认参数
        params.isaffirmanceSrc = queryParams.isaffirmanceSrc || "";
        params.isaffirmance = queryParams.isaffirmance || "";
        params.reEdit = queryParams.reEdit || "";

        API_REQ.getRightMenu(params).then(data => {
            data.rightMenus && data.rightMenus.sort((o1, o2) => {
                return o1.order - o2.order;
            });
            let _data = cloneDeep(data);
            this.checkShareBtn(_data)
            this.setRightMenu(data, false)
        });
    }

    @action('加载流程连续处理信息')
    loadContinuationProcessInfo = (queryParams, updateReqInfoFunc) => {
        if(queryParams.isOpenContinuationProcess == '1' && !queryParams.isRefresh == '1') {//连续处理进来，且不是刷新表单，获取连续处理信息
            let continuationProcessParams = continuationProcessUtil.getContinuationProcessParams();
            API_REQ.getContinnuationProcessInfo({viewScope: "doing", currentRequestId : queryParams.requestid, ...continuationProcessParams}).then(data => {
                if(data.isOpenContinuationProcess && data.currentIndex >= 0) {
                    this.continuationProcessInfo = {loaded : true, currentIndex : data.currentIndex, counts : data.count, requestId : queryParams.requestid}
                } else {
                    this.urlParams.isOpenContinuationProcess = '0';
                }
                //更新请求信息及刷新待办，这里加3S延时，防止前一条流程提交完毕时，刷列表的事件被覆盖
                window.setTimeout(function(){
                    updateReqInfoFunc();
                }, 3000);
            })
        } else {
            //更新请求信息及刷新待办
            updateReqInfoFunc();
        }

        //连续处理保存表单刷新流程，直接取上次的连续处理信息显示
        if(queryParams.isOpenContinuationProcess == '1' && queryParams.isRefresh == '1') {
            this.continuationProcessInfo = {
                loaded : true,
                isRefresh : '1',
                currentIndex : queryParams.currentIndex,
                counts : queryParams.counts,
                requestId : queryParams.requestid
            }
        }
    }

    //判断是否显示分享按钮
    checkShareBtn = (data) => {
        const fn = () => {
            ecCom.WeaTools.checkJoin().then(res => {
                let { dingTalkShareSwitch = 0, emSwitch = 0, joinStatus = false, msgShowType, status, webSwitch = 0, wxWorkShareSwitch = 0, shareWorkflow = 0 } = res;
                let ua = window.navigator.userAgent;
                shareWorkflow = joinStatus == true && shareWorkflow == 1;
                if (/.*E-Mobile7.*/.test(ua) || /.*E-Mobile\/7.*/.test(ua)) {//Emobile7环境
                    shareWorkflow = shareWorkflow && emSwitch == 1;
                } else if (/.*MicroMessenger.*/.test(ua)) {//微信
                    shareWorkflow = shareWorkflow && wxWorkShareSwitch == 1;
                } else if (/.*DingTalk.*/.test(ua)) {//钉钉
                    shareWorkflow = shareWorkflow && dingTalkShareSwitch == 1;
                }
                this.setRightMenu(data, shareWorkflow)
            })
        }
        this.pushJSCompleteEvent(fn);
    }

    @action('设置右键菜单')
    setRightMenu = (data = {}, shareWorkflow) => {
        if (!shareWorkflow) {//屏蔽分享按钮
            data.rightMenus && data.rightMenus.length > 0 ? data.rightMenus = data.rightMenus.filter(item => item.type !== "BTN_SHARE") : "";
        }
        let rightMenuNames = {};//右键菜单对应的自定义名称
        data.rightMenus && data.rightMenus.length > 0 && data.rightMenus.map(item => {
            const { systemMenuType = '', systemSmallType = 0, menuName = '' } = item;
            if (systemMenuType.length > 0 && menuName.length > 0) {
                rightMenuNames[`${systemMenuType}_${systemSmallType}`] = menuName;
            }
        })
        data.rightMenuNames = rightMenuNames;
        this.rightMenu = data;

        //流程点击流转设置保存流程时，重新打开流转设置
        const { requestid = -1 } = this.commonParam;
        const { isAllowNodeFreeFlow, isFree } = data;
        let isDefaultOpenFreeFlowSetDialog = window.localStorage.getItem('WfFormIsDefaultOpenFreeFlowSetDialog');
        if (requestid > 0 && isDefaultOpenFreeFlowSetDialog == '1' && (isAllowNodeFreeFlow == '1' || isFree == '1')) {
            window.localStorage.removeItem('WfFormIsDefaultOpenFreeFlowSetDialog');
            if (this.JSComplete) {
                doFreeWorkflow();
            } else {
                this.JSCompleteEvent.push(doFreeWorkflow);
            }
        }
    }

    @action('改变提交参数')
    changeSubmitParam = (param = {}) => {
        this.submitParam = { ...this.submitParam, ...param };
    }

    @action('设置提交到指定节点')
    setSubmitToNodeId = (isFromSubmitToReject = false) => {
        const { isSubmitDirectNode, lastnodeid } = this.rightMenu;
        let { canSubmitToRejectNode = true } = this.commonParam;
        if (this.variableMap.has('canSubmitToRejectNode')) {
            canSubmitToRejectNode = this.variableMap.get('canSubmitToRejectNode');
        }
        if ((isSubmitDirectNode == '1' || isFromSubmitToReject) && canSubmitToRejectNode) {
            this.changeSubmitParam({ SubmitToNodeid: lastnodeid });
        }
    }

    @action('设置关闭是否需要提示')
    setCloseNeedPrompt = (bool = true) => {
        this.closeNeedPrompt = bool;
    }

    @action('控制右键弹窗')
    controlDialogVisible = (key, value) => {
        this.dialogVisible.set(key, value);
    }

    @action('加载签字意见输入信息')
    loadMarkInfo = () => {
        const { isHideInput = '0', wfTestStr, requestType, intervenorright } = this.commonParam;
        let signInputParams = { ...this.baseParam };
        signInputParams.wfTestStr = wfTestStr;
        if (isHideInput != '1' && (requestType > 0 || intervenorright > 0)) {
            this.setBtnDisabled(true);
            API_REQ.getSignInput(signInputParams).then(data => {
                data.hasLoadMarkInfo = true;
                const { remarkquote = [] } = data;
                this.setMarkInfo(data);
                const { remarkInfo = {} } = data;
                //设置默认值到submitParams
                const updateParams = {
                    'remark': remarkInfo['remark'],
                    'field-annexupload': remarkInfo['field-annexupload'],
                    'signdocids': remarkInfo['signdocids'],
                    'signworkflowids': remarkInfo['signworkflowids'],
                    'remarkLocation': remarkInfo['remarkLocation']
                }
                this.changeSubmitParam(updateParams);
                this.setBtnDisabled(false);
                let remarkQuoteDatas = observable.map ? observable.map({}) : asMap({});;
                remarkquote.forEach((v, i) => {
                    remarkQuoteDatas.set(`key_${i}`, v);
                });
                this.controlVariableMap('remark_list', remarkQuoteDatas);
                this.controlVariableMap('remark_list_index', remarkquote.length);
				this.btnLabelName = data.btnLabelName;
            });
        } else {
            API_REQ.getNodeSignSet(signInputParams).then(data => {
                this.setMarkInfo(data);
            });
            this.setBtnDisabled(false);
        }
    }

    @action
    setMarkInfo = (data = {}) => {
        this.markInfo = data;
    }

    @action("加载流程干预信息")
    loadInterventionInfo = () => {
        const { intervenorright = 0 } = this.commonParam;
        if (intervenorright > 0) {
            API_REQ.getReqInterventionInfo(this.commonApiParam).then(data => {
                this.setInvertionInfo(data);
                this.changeSubmitParam(Util.getIntervenorDefaultV(data));
            })
        }
    }

    @action
    setInvertionInfo = (data = {}) => {
        this.invertionInfo = { ...this.invertionInfo, ...data };
    }

    @action("流程干预切换节点")
    getInterventionUser = (selectednodeinfo = {}) => {
        API_REQ.getInterventionUser({ ...this.commonApiParam, ...selectednodeinfo }).then((data) => {
            this.setInvertionInfo(data);
            this.changeSubmitParam(Util.getIntervenorDefaultV(data));
        });
    }

    @action("重置状态")
    resetStore = () => {
        this.promptInfo = {};
    }

    @action("获取扩展Tab")
    loadCustomTab = () => {
        const _this = this;
        API_REQ.getFormTab(this.commonApiParam).then((data = {}) => {
            const { customTabs = [] } = data;
            const customFiles = [];
            customTabs.map((tab = {}, index) => {
                const { filePath = '' } = tab;
                if (filePath.endsWith(".js")) {
                    customFiles.push(filePath);
                }
            });
            if (customTabs.length > 0) {
                _this.controlVariableMap("customTabs", customTabs);
                const init = () => {
                    if(window.console) console.log("customFiles加载成功！")
                }
                loadjs.isDefined('workflowCustomTab') ? loadjs.ready('workflowCustomTab', init) : loadjs(customFiles, 'workflowCustomTab', init);
            }
        });
    }

    @action("修改表单密级信息")
    setSecLevelInfo = (obj) => {
        this.secLevelInfo = { ...this.secLevelInfo, ...obj };
    }

    @action("更新commonParam值")
    updateCommonParam = (k, v) => {
        this.commonParam[k] = v;
    }

    @action("更新remindInfo")
    updateRemindInfo = (data = {}) => {
        this.remindInfo = { ...data };
    }

    @action("请求当前流程拥有的关注标签")
    getFormAttentionTag = () => {
        const { requestid, wfmonitor, f_weaver_belongto_userid, f_weaver_belongto_usertype, authSignatureStr, authStr, signatureAttributesStr, signatureSecretKey } = this.commonParam;
        if (wfmonitor)
            return;
        let params = {
            requestid,
            f_weaver_belongto_userid,
            f_weaver_belongto_usertype,
            authSignatureStr,
            authStr,
            signatureAttributesStr,
            signatureSecretKey
        }
        API_REQ.getFormAttentionTag(params).then(result => {
            //把结果跟在标题的后面
            const { titlename } = result;
            this.controlVariableMap("attention_titlename", titlename)
        })
    }

    @action("获取手写签批内容并放入变量区")
    changeHandWritingData = (type, val = []) => {
        this.controlVariableMap(type, val)
    }
    @action('设置流程二次确认提示信息')
    setPromptInfo = val => {
        this.promptInfo = val;
    }

    @action jumpTab = (queryParams = {}) => {
        //如果指定了tab,加载完成后跳到对应的tab
        if (queryParams.jumpTab) {
            this.setTabKey(queryParams.jumpTab);
        }
    }

    @action('冲突字段值记录')
    changeConflictFieldMap = (obj) => {
      if(typeof obj != 'object') return
        let keys = Object.keys(obj);
        keys.length > 0 && keys.map(key => {
            this.conflictFieldMap.set(key, obj[key]);
        })
    }

    /*-------------公文交换----------------*/
    @observable addInnerChangeBtn = false;//是否加载公文交换右键菜单
    @observable innerChangeDialog = false;//内部交换弹窗显隐

    @action
    setInnerChangeDialog = (bool) => {
        this.innerChangeDialog = bool;
    }

    @action('获取附件密级')
    getAccSecretLevelForDocid = (param) =>{
        return API_REQ.getAccSecretLevelForDocid(param);
    }

}